import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NettyServerHandler extends SimpleChannelInboundHandler<String> {
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    //事务组中的事务状态列表
    private static Map<String, List<String>> transactionTypeMap = new HashMap<>();

    //事务组中事务数量
    private static Map<String, Integer> transactionCountMap = new HashMap<>();

    //事务组是否已经接收到结束的标记
    private static Map<String, Boolean> isEndMap = new HashMap<>();

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.add(channel);
    }

    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("接受数据:"+ msg);

        JSONObject jsonObject = JSON.parseObject(msg);

        String command= jsonObject.getString("command");//create-创建事务组，add-添加事务
        String groupId= jsonObject.getString("groupId");//事务组id
//        String transactionId= jsonObject.getString("transactionId");//事务id
        String transactionType= jsonObject.getString("transactionType");//子事务类型, commit-待提交，rollback-待回滚
        Integer transactionCount = jsonObject.getInteger("transactionCount");//事务数量
        Boolean isEnd = jsonObject.getBoolean("isEnd");//是否结束事务

        if("create".equals(command)){
            //创建事务组
            transactionTypeMap.put(groupId, new ArrayList<>());
        }else if("add".equals(command)){
            //加入事务组
            List<String> transactionList = transactionTypeMap.get(groupId);
            transactionList.add(transactionType);

            if(isEnd){
                isEndMap.put(groupId, true);
                transactionCountMap.put(groupId, transactionCount);
            }

            //如果已经接收到事务结束的标记，比较事务是否全部到达，如果已经全部到达则看是否需要回滚
            JSONObject result = new JSONObject();
            result.put("groupId", groupId);
//            int transactionNum = transactionCountMap.get(groupId);
            if(isEndMap.get(groupId) && transactionCountMap.get(groupId) == transactionList.size()){
                if(transactionList.contains("rollback")){
                    result.put("command", "rollback");
                }else {
                    result.put("command", "commit");
                }
                send(result);
            }
        }
    }

    //发送数据
    private void send(JSONObject jsonObject){
        for(Channel channel:channelGroup){
            System.out.println("发送数据：" + jsonObject.toJSONString());
            channel.writeAndFlush(jsonObject.toJSONString());
        }

    }
}
